package com.ht.modules.system.online.cgform.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ht.entity.Result;
import com.ht.modules.system.online.cgform.entity.*;
import com.ht.modules.system.online.cgform.service.IOnlCgformHeadService;
import com.ht.modules.system.online.cgform.util.CgformUtil;
import com.ht.modules.system.online.codegenerate.database.DbReadTableUtil;
import com.ht.query.QueryGenerator;
import com.ht.utils.JwtUtil;
import com.ht.utils.oConvertUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.sql.SQLException;
import java.util.*;
@Slf4j
@RestController
@RequestMapping({"/online/cgform/head"})
public class OnlCgformHeadController {
    @Autowired
    private IOnlCgformHeadService onlCgformHeadService;
    private static String GENERATE_FORM_IDS;
    @Autowired
    @Lazy
    private DbReadTableUtil dbReadTableUtil;
    @GetMapping({"/list"})
    public Result<IPage<OnlCgformHead>> queryPageList(OnlCgformHead onlCgformHead, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<OnlCgformHead>> result = new Result<>();
        QueryWrapper<OnlCgformHead> queryWrapper = QueryGenerator.initQueryWrapper(onlCgformHead, req.getParameterMap());
        Page<OnlCgformHead> page = new Page<>((long) pageNo, (long) pageSize);
        IPage<OnlCgformHead> pageList = this.onlCgformHeadService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @PostMapping({"/add"})
    public Result<OnlCgformHead> add(@RequestBody OnlCgformHead onlCgformHead) {
        try {
            this.onlCgformHeadService.save(onlCgformHead);
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            throw new RuntimeException(var4.getMessage());
        }
        return Result.ok("添加成功!");
    }

    @PutMapping({"/edit"})
    public Result<OnlCgformHead> edit(@RequestBody OnlCgformHead onlCgformHead) {
        Result<OnlCgformHead> result = new Result<>();
        OnlCgformHead onlCgformHeadEntity = this.onlCgformHeadService.getById(onlCgformHead.getId());

        if (onlCgformHeadEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = this.onlCgformHeadService.updateById(onlCgformHead);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    @DeleteMapping({"/delete"})
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            this.onlCgformHeadService.deleteRecordAndTable(id, true);
        } catch (Exception var3) {
            return Result.error("删除失败" + var3.getMessage());
        }
        return Result.ok("删除成功!");
    }

    @DeleteMapping({"/removeRecord"})
    public Result<OnlCgformHead> removeRecord(@RequestParam(name = "id") String id) {
        Result<OnlCgformHead> result = new Result<>();
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(id);
        if (onlCgformHead == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = this.onlCgformHeadService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    @DeleteMapping({"/deleteBatch"})
    public Result<OnlCgformHead> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<OnlCgformHead> result = new Result<>();
        if (ids != null && !ids.trim().isEmpty()) {
            this.onlCgformHeadService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        } else {
            result.error500("参数不识别！");
        }

        return result;
    }

    @GetMapping({"/queryById"})
    public Result<OnlCgformHead> queryById(@RequestParam(name = "id") String id) {
        Result<OnlCgformHead> result = new Result<>();
        OnlCgformHead onlCgformHead = this.onlCgformHeadService.getById(id);
        if (onlCgformHead == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(onlCgformHead);
            result.setSuccess(true);
        }

        return result;
    }

    @PostMapping({"/enhanceJs/{code}"})
    public Result<?> saveEnhanceJs(@PathVariable("code") String code, @RequestBody OnlCgformEnhanceJs onlCgformEnhanceJs) {
        try {
            onlCgformEnhanceJs.setCgformHeadId(code);
            this.onlCgformHeadService.saveEnhance(onlCgformEnhanceJs);
            return Result.ok("保存成功!");
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/enhanceJs/{code}"})
    public Result<?> getEnhanceJs(@PathVariable("code") String code, HttpServletRequest req) {
        try {
            String type = req.getParameter("type");
            OnlCgformEnhanceJs obj = this.onlCgformHeadService.queryEnhance(code, type);
            return obj == null ? Result.error("查询为空") : Result.ok(obj);
        } catch (Exception var5) {
            log.error(var5.getMessage(), var5);
            return Result.error("查询失败!");
        }
    }

    @PutMapping({"/enhanceJs/{code}"})
    public Result<?> editEnhanceJs(@PathVariable("code") String code, @RequestBody OnlCgformEnhanceJs onlCgformEnhanceJs) {
        try {
            onlCgformEnhanceJs.setCgformHeadId(code);
            this.onlCgformHeadService.editEnhance(onlCgformEnhanceJs);
            return Result.ok("保存成功!");
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/enhanceButton/{formId}"})
    public Result<?> enhanceButton(@PathVariable("formId") String formId, HttpServletRequest req) {
        try {
            List<OnlCgformButton> list = this.onlCgformHeadService.queryButtonList(formId);
            return list != null && !list.isEmpty() ? Result.ok(list) : Result.error("查询为空");
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return Result.error("查询失败!");
        }
    }

    @PostMapping({"/enhanceSql/{formId}"})
    public Result<?> enhanceSql(@PathVariable("formId") String formId, @RequestBody OnlCgformEnhanceSql onlCgformEnhanceSql) {
        try {
            onlCgformEnhanceSql.setCgformHeadId(formId);
            this.onlCgformHeadService.saveEnhance(onlCgformEnhanceSql);
            return Result.ok("保存成功!");
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/enhanceSql/{formId}"})
    public Result<?> getEnhanceSql(@PathVariable("formId") String formId, HttpServletRequest req) {
        try {
            String buttonCode = req.getParameter("buttonCode");
            OnlCgformEnhanceSql obj = this.onlCgformHeadService.queryEnhanceSql(formId, buttonCode);
            return obj == null ? Result.error("查询为空") : Result.ok(obj);
        } catch (Exception var5) {
            log.error(var5.getMessage(), var5);
            return Result.error("查询失败!");
        }
    }

    @PutMapping({"/enhanceSql/{formId}"})
    public Result<?> editEnhanceSql(@PathVariable("formId") String formId, @RequestBody OnlCgformEnhanceSql onlCgformEnhanceSql) {
        try {
            onlCgformEnhanceSql.setCgformHeadId(formId);
            this.onlCgformHeadService.editEnhance(onlCgformEnhanceSql);
            return Result.ok("保存成功!");
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return Result.error("保存失败!");
        }
    }

    @PostMapping({"/enhanceJava/{formId}"})
    public Result<?> enhanceJava(@PathVariable("formId") String formId, @RequestBody OnlCgformEnhanceJava onlCgformEnhanceJava) {
        try {
            if (!CgformUtil.checkClassOrSpringBeanIsExist(onlCgformEnhanceJava)) {
                return Result.error("类实例化失败，请检查!");
            } else {
                onlCgformEnhanceJava.setCgformHeadId(formId);
                if (this.onlCgformHeadService.checkOnlyEnhance(onlCgformEnhanceJava)) {
                    this.onlCgformHeadService.saveEnhance(onlCgformEnhanceJava);
                    return Result.ok("保存成功!");
                } else {
                    return Result.error("保存失败,数据不唯一!");
                }
            }
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/enhanceJava/{formId}"})
    public Result<?> getEnhanceJava(@PathVariable("formId") String formId, OnlCgformEnhanceJava onlCgformEnhanceJava) {
        try {
            onlCgformEnhanceJava.setCgformHeadId(formId);
            OnlCgformEnhanceJava obj = this.onlCgformHeadService.queryEnhanceJava(onlCgformEnhanceJava);
            return obj == null ? Result.error("查询为空") : Result.ok(obj);
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return Result.error("查询失败!");
        }
    }

    @PutMapping({"/enhanceJava/{formId}"})
    public Result<?> editEnhanceJava(@PathVariable("formId") String formId, @RequestBody OnlCgformEnhanceJava onlCgformEnhanceJava) {
        try {
            if (!CgformUtil.checkClassOrSpringBeanIsExist(onlCgformEnhanceJava)) {
                return Result.error("类实例化失败，请检查!");
            } else {
                onlCgformEnhanceJava.setCgformHeadId(formId);
                if (this.onlCgformHeadService.checkOnlyEnhance(onlCgformEnhanceJava)) {
                    this.onlCgformHeadService.editEnhance(onlCgformEnhanceJava);
                    return Result.ok("保存成功!");
                } else {
                    return Result.error("保存失败,数据不唯一!");
                }
            }
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return Result.error("保存失败!");
        }
    }

    @GetMapping({"/queryTables"})
    public Result<?> queryTables(HttpServletRequest req) {
        String username = JwtUtil.getUserNameByToken(req);
        if (!"admin".equals(username)) {
            return Result.error("noadminauth");
        } else {
            new ArrayList<>();

            List<String> list;
            try {
                list = dbReadTableUtil.a();
            } catch (SQLException var9) {
                log.error(var9.getMessage(), var9);
                return Result.error("同步失败，未获取数据库表信息");
            }
            CgformUtil.sortStringList(list);
            List<String> onlineTables = this.onlCgformHeadService.queryOnlinetables();
            list.removeAll(onlineTables);
            List<Map<String, String>> result = new ArrayList<>();
            for (String str : list) {
                Map<String, String> map = new HashMap<>();
                map.put("id", str);
                result.add(map);
            }
            return Result.ok(result);
        }
    }

    @PostMapping({"/transTables/{tbnames}"})
    @RequiresRoles({"admin"})
    public Result<?> transTables(@PathVariable("tbnames") String tbnames, HttpServletRequest req) {
        String username = JwtUtil.getUserNameByToken(req);
        if (!"admin".equals(username)) {
            return Result.error("noadminauth");
        } else if (oConvertUtils.isEmpty(tbnames)) {
            return Result.error("未识别的表名信息");
        } else if (GENERATE_FORM_IDS != null && GENERATE_FORM_IDS.equals(tbnames)) {
            return Result.error("不允许重复生成!");
        } else {
            GENERATE_FORM_IDS = tbnames;
            String[] arr = tbnames.split(",");
            for (String s : arr) {
                if (oConvertUtils.isNotEmpty(s)) {
                    long count = this.onlCgformHeadService.count((new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, s));
                    if (count <= 0) {
                        log.info("[IP] [online数据库导入表]   --表名：{}", s);
                        this.onlCgformHeadService.saveDbTable2Online(s);
                    }
                }
            }

            GENERATE_FORM_IDS = null;
            return Result.ok("同步完成!");
        }
    }

    @GetMapping({"/rootFile"})
    public Result<?> rootFile() {
        JSONArray array = new JSONArray();
        File[] roots = File.listRoots();
        for (File f : roots) {
            JSONObject item = new JSONObject();
            if (f.isDirectory()) {
                System.out.println(f.getPath());
                item.put("key", f.getAbsolutePath());
                item.put("title", f.getPath());
                item.put("opened", false);
                JSONObject scopedSlots = new JSONObject();
                scopedSlots.put("icon", "custom");
                item.put("scopedSlots", scopedSlots);
                item.put("isLeaf", f.listFiles() == null || Objects.requireNonNull(f.listFiles()).length == 0);
            }
            array.add(item);
        }
        return Result.ok(array);
    }

    @GetMapping({"/fileTree"})
    public Result<?> fileTree(@RequestParam(name = "parentPath") String parentPath) {
        JSONArray array = new JSONArray();
        File file = new File(parentPath);
        File[] roots = file.listFiles();
        assert roots != null;
        for (File f : roots) {
            if (f.isDirectory() && oConvertUtils.isNotEmpty(f.getPath())) {
                JSONObject item = new JSONObject();
                System.out.println(f.getPath());
                item.put("key", f.getAbsolutePath());
                item.put("title", f.getPath().substring(f.getPath().lastIndexOf(File.separator) + 1));
                item.put("isLeaf", f.listFiles() == null || Objects.requireNonNull(f.listFiles()).length == 0);
                item.put("opened", false);
                JSONObject scopedSlots = new JSONObject();
                scopedSlots.put("icon", "custom");
                item.put("scopedSlots", scopedSlots);
                array.add(item);
            }
        }
        return Result.ok(array);
    }

    @Value("${code.projectPath}")
    private String projectPath;

    @GetMapping({"/tableInfo"})
    public Result<?> tableInfo(@RequestParam(name = "code") String code) {
        OnlCgformHead onlCgformHead = this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            return Result.error("未找到对应实体");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("main", onlCgformHead);
        // 有附表
        if (onlCgformHead.getTableType() == 2) {
            String subtable = onlCgformHead.getSubTableStr();
            if (oConvertUtils.isEmpty(subtable)) {
                return Result.error("类型为有附表的表单，附表信息不能为空!");
            }
            String[] subtableArray = subtable.split(",");
            List<OnlCgformHead> subList = this.onlCgformHeadService.list(new LambdaQueryWrapper<OnlCgformHead>()
                    .in(subtableArray.length > 0, OnlCgformHead::getTableName, Arrays.asList(subtableArray))
            );
            map.put("sub", subList);
        }
        map.put("projectPath", projectPath);
        return Result.ok(map);
    }
}
